import React, { useState, useEffect, useContext } from 'react';
import { connect } from 'dva';
import { Card, Button, Modal, Form, Input, message, Popconfirm } from 'antd';
import { PlusOutlined, ImportOutlined, ClearOutlined } from '@ant-design/icons';
import { FormInstance } from 'antd/lib/form';

import { filterAuth } from '@/support/common';
import CommonContext from '@/layouts/CommonContext';

import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoTable from '@/components/common/PateoTable';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';

import { ResponseInterface } from './types';
import styles from '@/components/common/PateoTable/TableList.less';
import UploadModal from './uploadModal';
import MaskText from '@/components/MaskText';

type GreyListProps = {
  greyListMng: any;
  dispatch: any;
  loading: boolean;
  location: { pathname: string };
};

interface GreyListDataItem {
  sid: number;
  vin: string;
  brandCode: string;
  brandName: string;
  seriesCode: string;
  seriesName: string;
  modelCode: string;
  modelName: string;
  carOwner: string;
  phone: string | number;
  [key: string]: any;
}

interface GreyListSearchField {
  vin?: string;
  brandCode?: string;
  seriesCode?: string;
  modelCode?: string;
  phone?: string;
}

interface CommonContext {
  permissions: Array<any>;
}

let searchFormRef: { current: FormInstance } | null = null;

const greyList: React.FC<GreyListProps> = props => {
  const {
    greyListMng: {
      pageData: { list, pagination },
    },
    dispatch,
    loading,
    location: { pathname = '/' },
  } = props;
  const { permissions } = useContext(CommonContext) as CommonContext;
  const [vinForm] = Form.useForm();
  const fetchList = ({ vin, brandCode, seriesCode, modelCode, phone }: GreyListSearchField) => {
    dispatch({
      type: 'greyListMng/getFetchPage',
      payload: {
        url: '/gray/management/list',
        vin,
        brandCode,
        seriesCode,
        modelCode,
        phone,
      },
    });
  };

  //  search form fields data
  const [brandList, setBrandList] = useState([]);
  const [brandCode, setBrandCode] = useState('');
  const [seriesList, setSeriesList] = useState([]);
  const [modelList, setModelList] = useState([]);
  const [searchParams, setSearchParams] = useState({});

  //  增改modal
  const [modalOpen, setModalOpen] = useState(false);
  const [modalTitle, setModalTitle] = useState('新增车辆');
  const [sid, setSid] = useState<number | null>(null);

  // 导入modal
  const [uploadModalOpen, setUploadModalOpen] = useState(false);

  const onRef = (ref: { current: FormInstance }) => {
    searchFormRef = ref;
  };

  useEffect(() => {
    dispatch({
      type: 'greyListMng/getData',
      payload: {
        url: '/common/vehicle/getcurrentbrand',
      },
      callback: (res: ResponseInterface<any>) => {
        setBrandList(res.data);
      },
    });
    fetchList(searchParams);
  }, []);

  useEffect(() => {
    !modalOpen && vinForm.resetFields(); // 关闭弹层 清空form
  }, [modalOpen]);

  useEffect(() => {
    return () => {
      dispatch({
        type: 'greyListMng/initData',
      });
    };
  }, []);

  /**
   * 获取车系数据
   * @param brandCode 品牌
   */
  const fetchSeriesList = (brandCode: string) => {
    setBrandCode(brandCode);
    dispatch({
      type: 'greyListMng/getData',
      payload: {
        url: '/common/vehicle/getserieslist',
        brandId: brandCode,
      },
      callback: (res: ResponseInterface<any>) => {
        setSeriesList(res.data);
      },
    });
  };

  /**
   * 获取车型数据
   * @param seriesCode 车系编码
   */
  const fetchModelList = (seriesCode: string) => {
    dispatch({
      type: 'greyListMng/getData',
      payload: {
        url: '/common/vehicle/gettypelist',
        brandId: brandCode,
        seriesId: seriesCode,
      },
      callback: (res: ResponseInterface<any>) => {
        setModelList(res.data);
      },
    });
  };

  /**
   * 编辑
   * @param record
   */
  const handleEdit = (record: GreyListDataItem) => {
    setModalTitle('编辑车辆');
    setModalOpen(true);
    setSid(record.sid);
    vinForm.setFieldsValue({
      vin: record.vin,
    });
  };

  /**
   * 删除
   * @param sid
   */
  const handleDel = (sid: number) => {
    dispatch({
      type: 'greyListMng/postDataWithRes',
      payload: {
        url: '/gray/management/delete',
        sid,
      },
      callback: (res: ResponseInterface<Object | null>) => {
        if (res.statusCode === '0') {
          message.success('删除成功');
          fetchList(searchParams);
        }
      },
    });
  };

  /**
   * 清空名单
   */
  const handleClearAll = () => {
    dispatch({
      type: 'greyListMng/postDataWithRes',
      payload: {
        url: '/gray/management/clear',
      },
      callback: (res: ResponseInterface<Object | null>) => {
        if (res.statusCode === '0') {
          message.success('清空成功');
          fetchList(searchParams);
        }
      },
    });
  };

  /**
   * 新增
   */
  const handleAdd = () => {
    setModalTitle('新增车辆');
    setModalOpen(true);
  };

  const closeModal = () => {
    setSid(null);
    setModalOpen(false);
  };

  /**
   * 修改信息
   */
  const handleSubmit = () => {
    const inputVal = vinForm.getFieldValue('vin');
    vinForm.setFieldsValue({ vin: inputVal.toUpperCase() }); // 输入统一转换大写
    vinForm
      .validateFields()
      .then(values => {
        dispatch({
          type: 'greyListMng/postDataWithRes',
          payload: {
            url: sid ? '/gray/management/edit' : '/gray/management/add',
            ...(sid && { sid }),
            ...values,
          },
          callback: (res: ResponseInterface<Object | null>) => {
            if (res.statusCode == '0') {
              message.success('保存成功');
              setModalOpen(false);
              fetchList(searchParams);
            }
          },
        });
      })
      .catch(err => {
        console.log('表单校验失败，失败原因:', err);
      });
  };

  const searchItems = [
    {
      title: 'VIN',
      type: 'input',
      key: 'vin',
    },
    {
      title: '品牌',
      type: 'select',
      selectOptions: brandList,
      keyValue: ['brandCode', 'brandName'],
      key: 'brandCode',
      onSelectChange: (val: string) => {
        searchFormRef?.current?.resetFields(['seriesCode', 'modelCode']);
        setSeriesList([]);
        val && fetchSeriesList(val);
      },
    },
    {
      title: '车系',
      type: 'select',
      selectOptions: seriesList,
      keyValue: ['code', 'name'],
      key: 'seriesCode',
      onSelectChange: (val: string) => {
        searchFormRef?.current?.resetFields(['modelCode']);
        setModelList([]);
        val && fetchModelList(val);
      },
    },
    {
      title: '车型',
      type: 'select',
      selectOptions: modelList,
      keyValue: ['code', 'name'],
      key: 'modelCode',
    },
    {
      title: '手机号码',
      type: 'input',
      key: 'phone',
    },
  ];

  const columns = [
    {
      title: 'VIN',
      dataIndex: 'vin',
    },
    {
      title: '品牌',
      dataIndex: 'brandName',
      // dataIndex: 'commandName',
    },
    {
      title: '车系',
      dataIndex: 'seriesName',
    },
    {
      title: '车型',
      dataIndex: 'modelName',
    },
    {
      title: '车主',
      dataIndex: 'carOwner',
      render(val: any) {
        return <MaskText text={val} type={'name'} />;
      },
    },
    {
      title: '手机号码',
      dataIndex: 'phone',
      render(val: any) {
        return <MaskText text={val} type="phone" />;
      },
    },
    {
      title: '操作',
      dataIndex: 'opt',
      fixed: 'right',
      width: 140,
      render: (text: any, record: GreyListDataItem) => {
        const btns = [
          {
            title: '编辑',
            key: 'edit',
            auth: 'greyList_edit',
            onConfirm: () => handleEdit(record),
          },
          {
            title: '删除',
            key: 'del',
            auth: 'greyList_del',
            message: '确认删除？删除后无法还原，请谨慎操作！',
            Popconfirm: true,
            onConfirm: () => handleDel(record?.sid),
          },
        ];
        return <PateoAuthButtons btns={btns} max={2} pathname={pathname} />;
      },
    },
  ];
  const paginationProps = {
    showSizeChanger: true,
    showQuickJumper: true,
    ...pagination,
    showTotal: () => <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>,
  };
  const tableProps = {
    columns,
    rowKey: (record: GreyListDataItem) => record.sid,
    loading,
    bordered: true,
    dataSource: list,
    pagination: paginationProps,
    scroll: { x: 'max-content' },
  };

  return (
    <>
      <Card bordered={false}>
        <PateoSearchForm
          onRef={onRef}
          searchItems={searchItems}
          fetchParams={{
            type: 'greyListMng/getFetchPage',
            url: '/gray/management/list',
          }}
          saveFormValues={(formValues: GreyListSearchField) => setSearchParams(formValues)}
          handleFormReset={() => setSearchParams({})}
        />
      </Card>

      <Card className={styles.standardTable}>
        <div className="my_newItem">
          {filterAuth('greyList_add', permissions, pathname) && (
            <Button size="small" icon={<PlusOutlined />} type="primary" onClick={() => handleAdd()}>
              新增车辆
            </Button>
          )}
          {filterAuth('greyList_import', permissions, pathname) && (
            <Button
              size="small"
              icon={<ImportOutlined />}
              type="primary"
              onClick={() => setUploadModalOpen(true)}
            >
              批量导入
            </Button>
          )}
          {filterAuth('greyList_clear', permissions, pathname) && (
            <Popconfirm
              title="确认清空？清空后无法还原，请谨慎操作！"
              onConfirm={handleClearAll}
              okText="确定"
              cancelText="取消"
            >
              <Button size="small" icon={<ClearOutlined />} type="default">
                清空名单
              </Button>
            </Popconfirm>
          )}
        </div>
        <PateoTable
          extraHandle={true}
          tableProps={tableProps}
          fetchParams={{
            type: 'greyListMng/getFetchPage',
            url: '/gray/management/list',
          }}
          formValues={searchParams}
          currentName="pageNo"
        />

        <Modal
          forceRender
          title={modalTitle}
          visible={modalOpen}
          onCancel={closeModal}
          okText="提交"
          onOk={handleSubmit}
        >
          <Form form={vinForm} name="vin">
            <Form.Item
              name="vin"
              label="VIN"
              rules={[
                { required: true, message: '请输入VIN码' },
                {
                  pattern: /^[A-Za-z0-9]{1,17}$/,
                  message: '格式错误：17 个字符，可包含英文字母（统一小写转大写）、数字',
                },
              ]}
            >
              <Input placeholder="请输入VIN码" maxLength={17} allowClear />
            </Form.Item>
          </Form>
        </Modal>

        {uploadModalOpen && (
          <UploadModal
            modalOpen={uploadModalOpen}
            closeModal={(refresh: Boolean = false) => {
              setUploadModalOpen(false);
              refresh && fetchList(searchParams);
            }}
          ></UploadModal>
        )}
      </Card>
    </>
  );
};

export default connect((state: any) => ({
  greyListMng: state.greyListMng,
  loading: state.loading.effects['greyListMng/getFetchPage'],
}))(greyList);
